package com.duojuhe.common.dbsource.config;

import com.duojuhe.common.dbsource.annotation.DataSourcesType;
import com.duojuhe.common.dbsource.holder.DynamicDataSourceContextHolder;
import com.duojuhe.common.dbsource.provider.DynamicDataSourceProvider;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

public class DynamicDataSource extends AbstractRoutingDataSource {

    DynamicDataSourceProvider dynamicDataSourceProvider;

    public DynamicDataSource(DynamicDataSourceProvider dynamicDataSourceProvider) {
        this.dynamicDataSourceProvider = dynamicDataSourceProvider;
        Map<String, DataSource> dataSourceMap = dynamicDataSourceProvider.loadDataSources();
        Map<Object, Object> targetDataSources = new HashMap<>(dataSourceMap);
        super.setTargetDataSources(targetDataSources);
        super.setDefaultTargetDataSource(dataSourceMap.get(DataSourcesType.master.name()));
        super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicDataSourceContextHolder.getDataSourceType();
    }


}